/**
 * 
 */
package com.cplsystems.incidencias.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.cplsystems.incidencias.app.utils.HibernateDAOSuportUtil;
import com.cplsystems.incidencias.business.Organizacion;
import com.cplsystems.incidencias.business.Persona;
import com.cplsystems.incidencias.dao.OrganizacionDAO;

/**
 * @author César Palalía López (csr.plz@aisa-automation.com)
 * 
 */
@Repository
public class OrganizacionDAOImpl extends HibernateDaoSupport implements
		OrganizacionDAO {

	@Autowired
	public void init(final SessionFactory sessionFactory)
			throws DataAccessException {
		setSessionFactory(sessionFactory);
	}

	@Transactional
	public void save(Organizacion organizacion) {
		try {
			getHibernateTemplate().saveOrUpdate(organizacion);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Organizacion> getCompaniasByNombreRFC(String compania,
			String rfc) {
		Criteria criteria = getHibernateTemplate().getSessionFactory()
				.openSession().createCriteria(Organizacion.class);
		criteria.add(Restrictions.like("nombre", "%" + compania + "%"));
		criteria.add(Restrictions.like("rfc", "%" + rfc + "%"));
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Organizacion> getCompaniasByNombre(String compania) {
		Criteria criteria = getHibernateTemplate().getSessionFactory()
				.openSession().createCriteria(Organizacion.class);
		criteria.add(Restrictions.like("nombre", "%" + compania + "%"));
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Organizacion> getCompaniasByRFC(String rfc) {
		Criteria criteria = getHibernateTemplate().getSessionFactory()
				.openSession().createCriteria(Organizacion.class);
		criteria.add(Restrictions.like("rfc", "%" + rfc + "%"));
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public Organizacion getOrganizacionByResponsable(Persona persona) {
		List<Organizacion> organizaciones = getHibernateTemplate().find(
				"FROM Organizacion as o WHERE o.responsable = ? ", persona);
		return organizaciones.size() > 0 ? organizaciones.get(0) : null;
	}

}
